package com.ncbee.base.web;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.ncbee.base.config.shiro.annotation.RequiresExtPermissions;
import com.ncbee.base.model.entity.Role;
import com.ncbee.base.model.entity.RoleResource;
import com.ncbee.base.service.RoleResourceService;
import com.ncbee.base.service.RoleService;
import com.ncbee.base.web.base.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author youdianyun
 * @since 2018-11-23
 */
@Controller
@RequestMapping("/role")
@RequiresExtPermissions("role:")
public class RoleController extends BaseController<Role> {
    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleResourceService roleResourceService;


    @Override
    protected IService<Role> getTargetService() {
        return roleService;
    }

    @Override
    public String getListPageUrl() {
        return "role/listPage";
    }

    @Override
    protected String getAddPageUrl() {
        return "role/addPage";
    }

    @Override
    protected String getEditPageUrl() {
        return "role/editPage";
    }

    @Override
    protected void beforeSave(HttpServletRequest request, Role entity) {
        entity.setCreateTime(LocalDateTime.now());
    }

    @Override
    protected void beforeUpdate(HttpServletRequest request, Role entity) {
        entity.setUpdateTime(LocalDateTime.now());
    }
    /*
     *
     */
    @RequestMapping("grantPage")
    public String grantPage(Long id,HttpServletRequest request){
      Role role=roleService.getById(id);
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("role_id",id);
      List<RoleResource> roleResourceList= roleResourceService.list(queryWrapper);
       String roleResourceListStr=JSONObject.toJSONString(roleResourceList);
      request.setAttribute("role",role);
      request.setAttribute("roleResourceList",roleResourceListStr);
     return "role/grantPage";
    }
    @ResponseBody
    @RequestMapping("grantResourceToRole")
    public Object grantResourceToRole(Long roleId,String resourceIds){
        boolean result=roleService.grantResourceToRole(roleId,resourceIds);
        if(result){
           return  renderSuccess();
        }
        return renderError();
    }
}

